package com.gopay.bis.web.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.manager.bank.BisBankInfoMainQueryManager;
import com.gopay.common.domain.bis.BisBankInfoMain;
import com.gopay.common.exception.GopayException;

/**
 * 银行信息查询
 * @author liujy
 *
 */
@Controller
@Scope("prototype")
public class BisBankInfoController {
	
	private static Logger logger = LoggerFactory.getLogger(BisBankInfoController.class);

	
	@Resource(name = "bisBankInfoMainQueryManager")
	private BisBankInfoMainQueryManager bisBankInfoMainQueryManager;

	/**
	 * 银行图标
	 * @param request
	 * @param response
	 * @throws GopayException
	 * @throws IOException
	 * @throws SQLException
	 */
	@RequestMapping(value = "/outputBankPic", method = { RequestMethod.GET })
	@ResponseBody
	protected void outputBankPic(HttpServletRequest request,
			HttpServletResponse response) {

		String bankCode = request.getParameter("bankCode");
		ServletOutputStream out = null;
		BufferedInputStream imgStream = null;
		try {
			out = response.getOutputStream();
			
			// 获取银行记录
			BisBankInfoMain bankInfo = bisBankInfoMainQueryManager.getByCode(bankCode);
			if (bankInfo == null) {
				throw new GopayException(ProcCodeConstants.PROC_CODE_100E5041);
			}
			
			Blob photoBlob = bankInfo.getBankPic();
			int nSize = 0;
			byte[] bye;
			int size = -1;
			if (photoBlob != null) {
				imgStream = new BufferedInputStream(photoBlob.getBinaryStream());
				nSize = (int) photoBlob.length();
				bye = new byte[nSize];
				size = imgStream.read(bye, 0, bye.length);
				out.write(bye, 0, size);
			}
		} catch (Exception e) {
			logger.error("bankCode不存在或读取图标异常：" + bankCode, e);
			if(null != out){
				try {
					out.print(bankCode);
				} catch (IOException e1) {
					logger.error("bankCode图标写入异常：" + bankCode, e);
				}
			}
		}finally {
			try {
				if (null != out) {
                    out.close();
                }
				if (null != imgStream) {
                    imgStream.close();
                }
			} catch (IOException e) {
				logger.error("关闭IO流异常： ", e);
			}
		}
	}	
}